<template>
  <div class="box-all">
    <el-dialog width="600px" title="批量操作" v-model="dialogFormVisible" :draggable="true" @close="dialogClose">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleChange">
        <el-tab-pane :disabled="loading" label="批量入库" :name="1">
          <div class="f-box">
            1、先下载导入模版，根据模版提示填写好内容后再上传
            <el-button @click="downTemp">下载模板</el-button>
          </div>
          <div class="t-box">
            2、上传填写好后的文件，文件格式xls、xlsx格式的文件
            <div class="upload-box">
              <el-button style="margin:auto;" @click="uploadFile">选择上传文件</el-button>
              <div class="file-box" v-show="fileForm.file">
                <span>{{ fileForm.fileName }}</span>
                <el-icon class="icon-item" @click="deleteFile">
                  <Close />
                </el-icon>
              </div>
            </div>
            <div v-show="errMsg" style="font-size:12px;color:#f40;">{{ errMsg }}</div>
          </div>
        </el-tab-pane>
        <el-tab-pane :disabled="loading" label="批量退库" :name="2">
          <div class="f-box">
            1、先下载导入模版，根据模版提示填写好内容后再上传
            <el-button @click="downTemp">下载模板</el-button>
          </div>
          <div class="t-box">
            2、上传填写好后的文件，文件格式xls、xlsx格式的文件
            <div class="upload-box">
              <el-button style="margin:auto;" @click="uploadFile">选择上传文件</el-button>
              <div class="file-box" v-show="fileForm.file">
                <span>{{ fileForm.fileName }}</span>
                <el-icon class="icon-item" @click="deleteFile">
                  <Close />
                </el-icon>
              </div>
            </div>
            <div v-show="errMsg" style="font-size:12px;color:#f40;">{{ errMsg }}</div>
          </div>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-link type="primary" @click="toInHis">入库历史</el-link>
          <el-link style="margin-left:10px;" type="primary" @click="toOutHis">退库历史</el-link>
          <el-button style="margin-left:auto;" @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHandle">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <input ref="uploadInputRef" style="display:none" type="file"
    accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" @change="uploadChange">
  <in-his ref="inHisRef" />
  <out-his ref="outHisRef" />
</template>

<script>
import { reactive, ref, toRefs } from 'vue'
import { BlobDownLoad, getStore, successDeal, warningDeal } from '@/utils/utils'
import axios from "axios"
import _http from '@/utils/http'
import api from '../api'
import inHis from './inHis.vue'
import outHis from './outHis.vue'
export default {
  components: {
    inHis,
    outHis,
  },
  setup(props, context) {
    const uploadInputRef = ref(null)
    const inHisRef = ref(null)
    const outHisRef = ref(null)

    const state = reactive({
      errMsg: '',
      loading: false,
      activeName: 1,
      dialogFormVisible: false,
      fileForm: {},
    })

    function dialogShow(i) {
      state.activeName = i
      state.dialogFormVisible = true
    }

    function downTemp() {
      const obj = {
        responseType: 'blob',
      }
      _http('get', {
        url: `/eas/manage/cardInventory/download/template/${state.activeName}`,
        apiName: '下载模板 - type : 1-入库，2-出库',
      }, obj, true, {}).then(res => {
        const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
        BlobDownLoad(res, _fileName)
      }).catch(err => {
        console.log(err)
      })
    }

    function dialogClose() {
      state.errMsg = null
      state.fileForm = {}
    }

    function uploadFile() {
      uploadInputRef.value.click()
    }

    //上传文件
    async function uploadChange(e) {
      state.fileForm = {}
      state.fileForm.file = e.target.files[0]
      state.fileForm.fileName = e.target.files[0].name
      // await uploadFile(fileForm)
      uploadInputRef.value.value = ''
    }

    function deleteFile() {
      state.fileForm = {}
    }

    function submitHandle() {
      if (state.fileForm && state.fileForm.file) {
        const token = window.localStorage.getItem("USER_TOKEN") || '';
        const uesrInfo = getStore("USER_INFO") || {};
        const Authorization = getStore("USER_AUTHOR") || {
          Authorization: `'','','',3,20,''`,
        };
        state.errMsg = null
        let param = new FormData()
        param.append('file', state.fileForm.file, state.fileForm.fileName)
        let config = {
          headers: {
            token: token ? `Bearer ${token}` : '',
            username: uesrInfo.username || '',
            'Content-Type': 'multipart/form-data',
            Authorization: Authorization.Authorization,
            platformHeadType: 'ilinkPlatform',
          }
        }
        if (state.activeName == 1) {
          let url = '/eas/manage/cardInventory/import/in'
          if (PROCESS_ENV.ENVIRONMENT == 'Production') {
            url = '/coupon_h5' + url
          }
          axios.post(url, param, config).then(res => {
            if (res.data.code == '200') {
              successDeal(res.data.msg)
              context.emit('dialogClose')
              state.dialogFormVisible = false
            } else {
              warningDeal(res.data.msg)
            }
            state.loading = false
          }).catch(err => {
            console.log(err)
            state.loading = false
          })
        } else if (state.activeName == 2) {
          let url = '/eas/manage/cardInventory/import/out'
          if (PROCESS_ENV.ENVIRONMENT == 'Production') {
            url = '/coupon_h5' + url
          }
          axios.post(url, param, config).then(res => {
            if (res.data.code == '200') {
              successDeal(res.data.msg)
              context.emit('dialogClose')
              state.dialogFormVisible = false
            } else {
              warningDeal(res.data.msg)
            }
            state.loading = false
          }).catch(err => {
            console.log(err)
            state.loading = false
          })
        }
      } else {
        state.errMsg = '请选择上传文件'
      }
    }

    function handleChange() {
      state.fileForm = {}
    }

    function toInHis() {
      inHisRef.value.dialogShow()
    }

    function toOutHis() {
      outHisRef.value.dialogShow()
    }

    return {
      ...toRefs(state),
      uploadInputRef,
      inHisRef,
      outHisRef,
      dialogShow,
      dialogClose,
      uploadChange,
      uploadFile,
      deleteFile,
      submitHandle,
      downTemp,
      handleChange,
      toInHis,
      toOutHis,
    }
  }
}
</script>

<style lang="scss" scoped>
.f-box,
.t-box {
  box-sizing: border-box;
  padding: 20px;
  background-color: rgba($color: #0081ff, $alpha: 0.1);
  display: flex;
  flex-flow: column;
  align-items: flex-start;
  gap: 10px;
}
.t-box {
  margin-top: 20px;
  .upload-box {
    width: 100%;
    box-sizing: border-box;
    padding: 50px 20px;
    display: flex;
    border: 1px dashed #dcdee0;
    background-color: #ffffff;
    flex-flow: column;
    .file-box {
      width: 100%;
      margin-top: 20px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      transition: all 0.3s;
      background-color: rgba($color: #0081ff, $alpha: 0.1);
      box-sizing: border-box;
      padding: 5px;
      &:hover {
        background-color: rgba($color: #0081ff, $alpha: 0.2);
      }
      .icon-item {
        cursor: pointer;
      }
    }
  }
}
.dialog-footer {
  display: flex;
  align-items: center;
}
</style>